package com.wl.studyjob.dbchange.zk;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import java.util.Properties;

public class ClientDb {

    private ZkClient zkClient = null;
    private Properties pro = null;
    BasicDataSource dataSource = null;

    public Properties getConnet() throws Exception {
        zkClient = new ZkClient("linux121:2181,linux122:2181,linux123:2181");

        pro = (Properties) zkClient.readData("/dbservers/db");
        dataSource = BasicDataSourceFactory.createDataSource(pro);

        System.out.println("变更前的连接池信息："+ pro);

        zkClient.subscribeDataChanges("/dbservers/db", new IZkDataListener() {
            public void handleDataChange(String dataPath, Object data) throws Exception {

                dataSource.close();

                dataSource = BasicDataSourceFactory.createDataSource((Properties) data);

                System.out.println("变更后的连接池信息" + (Properties) data);

            }

            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("连接池信息已被删除！！！");
            }
        });

        return pro;

    }

}
